<template>
  <div class="app-container">
    <!-- <div id="map"></div> -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="规则名称" prop="ruleName">
        <el-input
          v-model="queryParams.ruleName"
          placeholder="请输入会员卡规则名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          v-hasPermi="['business:memCardRule:query']"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:memCardRule:add']"
          >新增</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single"
          v-hasPermi="['business:memCardRule:edit']">修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete()"
          v-hasPermi="['business:memCardRule:del']"
          >删除</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="storeList"
      max-height="650px"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
    

      <el-table-column
        label="所属区域"
        align="center"
        prop="belongRegionName"
        width="120"
      />
      <el-table-column
        label="所属门店"
        align="center"
        prop="mainStoreName"
        width="120"
      />
      <el-table-column label="会员卡名称" align="center" prop="ruleName" />
      

      
      <el-table-column label="允许使用门店" align="center" prop="storeNames" />
      <!-- <el-table-column label="总状态" align="center" prop="status" >
                <template slot-scope="scope">
                    <span v-if="scope.row.status==0">待处理</span>
                    <span v-if="scope.row.status==1">已同意</span>
                    <span v-if="scope.row.status==2">已取消</span>
                </template>
</el-table-column> -->
      <el-table-column label="己方状态" align="center" prop="status1">
        <template slot-scope="scope">
          <span v-if="scope.row.status1 == 0">待审批</span>
          <span v-if="scope.row.status1 == 1">已同意</span>
          <span v-if="scope.row.status1 == 2">已取消</span>
        </template>
      </el-table-column>

      <el-table-column label="己方审核人" align="center" prop="checkBy" />
      <el-table-column label="己方审核时间" align="center" prop="checkTime" />


      <el-table-column label="使用方状态" align="center" prop="status2">
        <template slot-scope="scope">
          <span v-if="scope.row.status2 == 0">待审批</span>
          <span v-if="scope.row.status2 == 1">已同意</span>
          <span v-if="scope.row.status2 == 2">已取消</span>
        </template>
      </el-table-column>
      <el-table-column label="使用方审核人" align="center" prop="checkByBy" />
      <el-table-column label="使用方审核时间" align="center" prop="checkTimeBy" />

      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="修改人" align="center" prop="updateBy" />
      <el-table-column label="修改时间" align="center" prop="updateTime" />


      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
        width="250"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            v-if="scope.row.status1 != 1"
            icon="el-icon-check"
            v-hasPermi="['system:memCardRule:cancle']"
            @click="agreeUpdate(scope.row, 1)"
            >同意</el-button
          >

          <el-button
            size="mini"
            type="text"
            v-if="scope.row.status1 != 2"
            icon="el-icon-close"
            v-hasPermi="['system:memCardRule:cancle']"
            @click="agreeUpdate(scope.row, 2)"
            >取消</el-button
          >

          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-hasPermi="['system:memCardRule:edit']"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:memCardRule:del']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改规则 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="600px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="所属区域">
          <el-select
            :disabled="title == '修改规则'"
            clearable
            v-model="form.tampRegionId"
            @change="changeCurrentRegion"
          >
            <el-option
              v-for="(item, index) of region"
              :key="index"
              :label="item.value"
              :value="item.key"
              >{{ item.value }}</el-option
            >
          </el-select>
        </el-form-item>
        <el-form-item label="主门店">
          <el-select
            :disabled="title == '修改规则'"
            clearable
            v-model="form.storeId"
            @change="storeChange"
          >
            <el-option
              v-for="(item, index) of currentStore"
              :key="index"
              :label="item.value"
              :value="item.key"
              >{{ item.value }}</el-option
            >
          </el-select>
        </el-form-item>
        <el-form-item label="规则名称" prop="memberRuleId">
          <el-select
            :disabled="title == '修改规则'"
            clearable
            v-model="form.memberRuleId"
            @change="memberCardChange"
            multiple
          >
            <el-option
              v-for="(item, index) of storeMember"
              :key="index"
              :label="item.value"
              :value="item.key"
              >{{ item.value }}</el-option
            >
          </el-select>
        </el-form-item>
        <el-form-item label="区域" prop="byRegionIds">
          <el-select
            clearable
            v-model="form.byRegionIds"
            @change="changeRegion"
            multiple
          >
            <el-option
              v-for="(item, index) of region"
              :key="index"
              :label="item.value"
              :value="item.key"
              >{{ item.value }}</el-option
            >
          </el-select>
        </el-form-item>
        <el-form-item label="允许使用门店" prop="byStoreIds">
          <el-select
            clearable
            v-model="form.byStoreIds"
            @change="changeStore"
            multiple
          >
            <el-option
              v-for="(item, index) of ascriptionStore"
              :key="index"
              :label="item.value"
              :value="item.key"
              >{{ item.value }}</el-option
            >
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listRule,
  listStoreMember,
  delMemberRule,
  addMemberRule,
  zyMemberCrossCheck,
  updateMemberRule,
  listMemberRegion,
  listMemberStore,
  submitCross,
  deleteRule,
  getMemberRule,
  getDetail,
} from "@/api/system/card/ruleSetting";
import { allListfreePermissions } from "@/api/system/personnel/region";
export default {
  name: "ruleSetting",
  data() {
    return {
      // map: null,
      local: null,
      mk: null,
      latitude: "",
      longitude: "",
      keyWords: "",
      result: "",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 门店表格数据
      storeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      crossStore: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ruleName: null,
        days: null,
        createTime: null,
        storeName: null,
        phoneNumber: null,
        province: null,
        provinceString: null,
        city: null,
        cityString: null,
        county: null,
        countyString: null,
        detail: null,
        longitude: null,
        latitude: null,
        intro: null,
        images: null,
        status: null,
        isInitiate: null,
        openingTime: null,
        closingTime: null,
        isShow: null,
      },
      // 提交表单参数
      form: {
        byStoreIds: [],
      },
      subForm: {},
      subRules: {
        regionId: [
          { required: true, message: "请填选适用区域", trigger: "blur" },
        ],
        storeId: [
          { required: true, message: "请选择当前门店", trigger: "blur" },
        ],
        storeId: [
          { required: true, message: "请选择归属门店", trigger: "blur" },
        ],
      },
      // 表单校验
      rules: {
        // 会员卡id
        memberRuleId: [
          { required: true, message: "请填选会员卡", trigger: "blur" },
        ],
        // 归属门店id数组
        byStoreIds: [
          { required: true, message: "请填选专属门店", trigger: "blur" },
        ],
        // 区域id
        byRegionIds: [
          { required: true, message: "请填选专属门店区域", trigger: "blur" },
        ],
      },
      options: [],
      List: [
        {
          key: 1,
          value: "营业中",
        },
        {
          key: 2,
          value: "未营业",
        },
      ],
      isShowList: [
        {
          key: 1,
          value: "是",
        },
        {
          key: 0,
          value: "否",
        },
      ],
      memberRuleId: "",
      region: [],
      // 当前门店
      currentStore: [],
      // 归属门店
      ascriptionStore: [],
      // 会员卡列表
      storeMember: [],
      subStore: [],
    };
  },
  created() {
    // 获取数据列表
    this.getList();
    this.listMemberRegion();
  },
  methods: {
    //跨店规则提交
    submitCross() {
      this.$refs["subForm"].validate((valid) => {
        const params = {
          byRegionIds: this.subForm.regionId.join(","),
          byStoreIds: this.subForm.storeId.join(","),
          memberRuleId: this.memberRuleId,
        };
        console.log(params);
        if (valid) {
          if (this.memberRuleId != "") {
            submitCross(params).then((response) => {
              if (response.code == 200) {
                this.$modal.msgSuccess("修改成功");
                this.crossStore = false;
                this.getList();
              }
            });
          } else {
            submitCross(this.subForm).then((response) => {
              if (response.code == 200) {
                this.$modal.msgSuccess("新增成功");
                this.crossStore = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    //关闭跨店弹窗
    crossStoreClose() {
      this.$refs["subForm"].resetFields();
      this.memberRuleId = "";
    },
    cancelCross() {
      this.$refs["subForm"].resetFields();
      this.memberRuleId = "";
      this.crossStore = false;
    },
    //跨店门店
    changeSubStore(value) {
      console.log("跨店门店", value);
    },
    //跨店区域
    changeSubRegion(value) {
      console.log("跨店区域", value);
      const byRegionIds = value.join(",");
      console.log(byRegionIds);
      listMemberStore({ byRegionIds: byRegionIds }).then((res) => {
        this.subStore = res.data.map((rItem) => {
          return {
            key: rItem.id,
            value: rItem.storeName,
          };
        });
      });
    },
    //跨店规则
    handleAddcrossStore(row) {
      this.memberRuleId = row.id;
      this.crossStore = true;
    },
    listMemberRegion() {
      listMemberRegion().then((res) => {
        this.region = res.data.map((rItem) => {
          return {
            key: rItem.id,
            value: rItem.regionName,
          };
        });
      });
    },
    // 搜索地址
    // setPlace() {
    //   this.local = new BMap.LocalSearch(this.map, {
    //     onSearchComplete: this.searchPlace,
    //   });
    //   this.local.search(this.form.detail);
    // },
    // searchPlace() {
    //   if (this.local.getResults() != undefined) {
    //     this.map.clearOverlays(); //清除地图上所有覆盖物
    //     if (this.local.getResults().getPoi(0)) {
    //       let point = this.local.getResults().getPoi(0).point; //获取第一个智能搜索的结果
    //       this.map.centerAndZoom(point, 18);
    //       this.handleMarker(this, point);
    //       console.log("经度：" + point.lng + "--" + "纬度" + point.lat);
    //       this.form.longitude = point.lng;
    //       this.form.latitude = point.lat;
    //       this.latitude = point.lat;
    //       this.longitude = point.lng;
    //     } else {
    //       this.$message.error("未匹配到地点!");
    //     }
    //   } else {
    //     this.$message.error("未找到搜索结果!");
    //   }
    // },
    // 设置标注
    // handleMarker(obj, point) {
    //   obj.mk = new BMap.Marker(point);
    //   obj.map.addOverlay(obj.mk);
    //   obj.mk.enableDragging(); // 可拖拽
    //   obj.mk.addEventListener("dragend", function (e) {
    //     // 监听标注的拖拽，获取拖拽后的经纬度
    //     this.latitude = point.lat;
    //     this.longitude = point.lng;
    //   });
    //   obj.map.panTo(point);
    // },
    handleChange() {
      console.log(this.form.province, 123);
    },
    // blurDetail() {
    //   const geocoder = new BMap.Geocoder();
    //   console.log(geocoder);
    //   geocoder.getPoint(
    //     this.form.detail,
    //     (point) => {
    //       if (point) {
    //         this.result = `经度：${point.lng}，纬度：${point.lat}`;
    //         console.log(this.result, 123);
    //       } else {
    //         this.result = "地址解析失败";
    //         console.log(this.result, 123);
    //       }
    //     },
    //     "北京市"
    //   );
    // },
    /** 查询数据列表 */
    getList() {
      this.loading = true;
      listRule(this.queryParams).then((response) => {
        this.storeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        storeName: null,
        phoneNumber: null,
        province: null,
        provinceString: null,
        city: null,
        cityString: null,
        county: null,
        countyString: null,
        detail: null,
        longitude: null,
        latitude: null,
        intro: null,
        images: null,
        status: null,
        byStoreIds: [],
        isInitiate: null,
        openingTime: null,
        closingTime: null,
        createTime: null,
        updateTime: null,
        isShow: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.listMemberRegion();
      this.title = "添加规则";
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      let ids = "";
      if (row) {
        ids = row.id;
      } else {
        ids = this.ids.join(",");
      }
      this.$modal
        .confirm('是否确认删除序号为"' + ids + '"的规则？')
        .then(function () {
          return deleteRule(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/store/export",
        {
          ...this.queryParams,
        },
        `store_${new Date().getTime()}.xlsx`
      );
    },

    // 切换当前区域
    changeCurrentRegion(value) {
      // const byRegionIds = value.join(",");
      const regionIds = value;
      listMemberStore({ regionIds: regionIds }).then((res) => {
        this.currentStore = res.data.map((rItem) => {
          return {
            key: rItem.id,
            value: rItem.storeName,
          };
        });
      });
    },
    // 切换归属区域
    changeRegion(value) {
      const regionIds = value.join(",");
      // this.form.byRegionIds = byRegionIds
      // 获取区域列表
      listMemberStore({ regionIds: regionIds }).then((res) => {
        this.ascriptionStore = res.data.map((rItem) => {
          return {
            key: rItem.id,
            value: rItem.storeName,
          };
        });
        this.ascriptionStore = this.ascriptionStore.filter(
          (item) => item.key != this.form.storeId
        );
      });
    },
    // 选择当前门店
    storeChange(value) {
      // 获取当前门店的会员卡的列表
      listStoreMember({ storeId: value }).then((res) => {
        this.storeMember = res.rows.map((rItem) => {
          return {
            key: rItem.id,
            value: rItem.ruleName,
          };
        });

        console.log(this.storeMember, "storeMember111");
      });
    },
    /** 提交按钮 */
    submitForm() {
      console.log(this.form, "22222");
      this.form.regionId =this.form.tampRegionId;
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let obj = JSON.parse(JSON.stringify(this.form));
          obj.byStoreIds = obj.byStoreIds.join(",");
          obj.byRegionIds = obj.byRegionIds.join(",");
          obj.memberRuleId = obj.memberRuleId[0];
          console.log(obj, "22222");

          if (obj.id != null) {
            console.log("编辑");
            updateMemberRule(obj).then((response) => {
              if (response.code != 500) {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addMemberRule(obj).then((response) => {
              if (response.code != 500) {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },

    // 归属门店切换
    changeStore(value) {
      this.form.byStoreIds = value;
    },
    // 会员卡切换
    memberCardChange(value) {
      this.form.memberRuleId = value;
      this.form.memberRuleIds = value.length > 0 ? value.join(",") : value;
    },
    //获取详情
    async getDetail(id) {
      const res = await getDetail(id);
      if (res.code == 200) {
        console.log(res, "rrrrrr");

        res.data.memberRuleId = [res.data.memberRuleId];
        if (res.data.byRegionIds) {
          res.data.byRegionIds = res.data.byRegionIds.includes(",")
            ? res.data.byRegionIds.split(",").map((item) => {
                item = Number(item);
                return item;
              })
            : res.data.byRegionIds.split().map((item) => {
                item = Number(item);
                return item;
              });
        }

        if (res.data.byStoreIds) {
          res.data.byStoreIds = res.data.byStoreIds.includes(",")
            ? res.data.byStoreIds.split(",").map((item) => {
                item = Number(item);
                return item;
              })
            : res.data.byStoreIds.split().map((item) => {
                item = Number(item);
                return item;
              });
        }

        if (res.data.byRegionIds) {
          this.changeRegion(res.data.byRegionIds);
        }
        this.form = res.data;
        this.form.tampRegionId = res.data.regionId * 1;
        this.form.storeId = res.data.storeId * 1;
        this.form.memberRuleId = res.data.memberRuleId * 1;

        this.changeCurrentRegion(this.form.tampRegionId);
        this.storeChange(this.form.storeId);
        console.log(this.currentStore, "currentStore");
        console.log(this.storeMember, "storeMember");
      } else {
        this.$message.error(res.msg || "获取规则详情失败");
      }
    },
    // 修改点击事件
    handleUpdate(row) {
      // this.form = row;
      this.open = true;
      this.title = "修改规则";
      this.getDetail(row.id);
      console.log(row);
    },
    // 同意 或不同意
    agreeUpdate(row, statusParam) {
      // this.form = row;
      const paramData = {
        id: row.id,
        status1: statusParam,
      };
      zyMemberCrossCheck(paramData).then((response) => {
        if (response.code != 500) {
          this.$modal.msgSuccess("操作成功");
          this.open = false;
          this.getList();
        }
      });
    },
  },
};
</script>
<style lang="scss">
.descStyle {
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-all;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
}

.tooltip {
  max-width: 600px;
}
</style>
